package me.kennylee.tongji;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>Created on 5/11/2017.</p>
 *
 * @author kennylee
 */
public abstract class ReportDataItemBuilder<T> {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final String json;

    public ReportDataItemBuilder(String json) {
        this.json = json;
    }

    /**
     * 构建实体列表。默认情况下有items节点下的把维度数据和精度数据作为参数给实体的构建方法，如果有子类差异请用重写即可。
     *
     * @return
     */
    public List<T> build() {
        List<T> list = new ArrayList<>();
        if (isSuccess()) {
            for (int i = 0, l = dimensionData().size(); i != l; i++) {
                JsonArray a = dimensionData().get(i).getAsJsonArray();
                JsonArray b = indexData().get(i).getAsJsonArray();

                ParameterizedType parameterizedType = (ParameterizedType) getClass()
                        .getGenericSuperclass();
                Type[] types = parameterizedType.getActualTypeArguments();
                @SuppressWarnings("unchecked")
                Class<T> clzz = (Class<T>) types[0];
                try {
                    T item = clzz.getConstructor(JsonArray.class, JsonArray.class).newInstance(a, b);
                    list.add(item);
                } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
        return list;
    }

    protected boolean isSuccess() {
        return ReportDataApiResponse.isSuccess(json);
    }

    protected String getJson() {
        return json;
    }

    protected JsonArray baseItems() {
        return getJsonObject().get("body").getAsJsonObject().get("data").getAsJsonArray().get(0)
                .getAsJsonObject().get("result").getAsJsonObject().get("items").getAsJsonArray();
    }

    private JsonObject getJsonObject() {
        return new Gson().fromJson(getJson(), JsonObject.class);
    }

    /**
     * items中的维度数据
     *
     * @return JsonArray
     */
    protected JsonArray dimensionData() {
        return baseItems().get(0).getAsJsonArray();
    }

    /**
     * items中的指标数据，对应维度和fields
     *
     * @return JsonArray
     */
    protected JsonArray indexData() {
        return baseItems().get(1).getAsJsonArray();
    }
}
